package cn.tworice.admin.web;

import cn.tworice.admin.service.LogService;
import cn.tworice.admin.service.LoginService;
import cn.tworice.common.entity.Admin;
import cn.tworice.common.entity.Resources;
import cn.tworice.common.entity.Student;
import cn.tworice.common.entity.dto.CompaniesDto;
import cn.tworice.common.entity.dto.ResourcesDto;
import cn.tworice.common.utils.RedisUtil;
import cn.tworice.common.utils.TokenUtil;
import com.lmk.core.web.support.api.RequestResult;
import com.lmk.core.web.support.api.StatusCode;
import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.IOException;
import java.util.List;
import java.util.UUID;


/**
 * 登录注册操作及登录页数据展示
 *
 * @author 二饭
 * @email 1786705138@qq.com
 */

@RestController
@RequestMapping("admin/login")
@Slf4j
@CrossOrigin
public class LoginController {

    @Autowired
    LoginService loginService;

    @Autowired
    private LogService logService;

    @Autowired
    private RedisUtil redisUtil;

    @ApiOperation("登录")
    @PostMapping()
    public RequestResult login(HttpServletRequest request, String username, String password,String verCode,String key,Integer type) {
        RequestResult result = new RequestResult();

        // 判断验证码
        if (verCode==null || !redisUtil.exist(key,verCode)) {
            logService.addLoginLog(username, password, 0); // 写入日志
            result.setCode(new StatusCode(400,"验证码错误"));
            return result;
        }
        result.appendData("type",type);
        if(type==3){
            // 判断账号密码是否正确
            Admin admin = loginService.checkLogin(username, password);
            if (admin == null) {
                result.setCode(new StatusCode(400, "用户名或密码有误"));
                logService.addLoginLog(username, password, 0); // 写入日志
            } else {
                // 判断账号是否被停用
                if (admin.getStatus() == -1) {
                    result.setCode(new StatusCode(400, "账户已被停用"));
                    logService.addLoginLog(username, password, 0);
                } else {
                    logService.addLoginLog(username, password, 1); // 写入日志
                    result.setCode(new StatusCode(200, "登录成功"));
                    // 登录成功生成Token
                    String token = TokenUtil.getAdminToken(admin);
                    // 构建返回客户端内容
                    result.appendData("token", token);
                    result.appendData("admin", admin);

                    // 登录成功获取该用户的权限资源
                    List<ResourcesDto> resources = loginService.getResourceById(admin.getId());
                    result.appendData("resources", resources);
                }
            }

        }else if(type==2){
            // 企业登录
            CompaniesDto companiesDto=loginService.companiesLogin(username, password);
            if(companiesDto==null){
                result.setCode(new StatusCode(400, "用户名或密码有误"));
                logService.addLoginLog(username, password, 0); // 写入日志
            }else{
                logService.addLoginLog(username, password, 1); // 写入日志
                result.setCode(new StatusCode(200, "登录成功"));

                // 构建返回客户端内容
                result.appendData("token", "qiye");
                result.appendData("admin", companiesDto);
                // 登录成功获取该用户的权限资源
                List<ResourcesDto> resources = loginService.getResourceByRole(3);
                result.appendData("resources", resources);
            }
        }else if(type==1){
            // 学生登录
            Student student=loginService.studentLogin(username, password);
            if(student==null){
                result.setCode(new StatusCode(400, "用户名或密码有误"));
                logService.addLoginLog(username, password, 0); // 写入日志
            }else{
                logService.addLoginLog(username, password, 1); // 写入日志
                result.setCode(new StatusCode(200, "登录成功"));

                // 构建返回客户端内容
                result.appendData("token", "student");
                result.appendData("admin", student);
                // 登录成功获取该用户的权限资源
                List<ResourcesDto> resources = loginService.getResourceByRole(4);
                result.appendData("resources", resources);
            }
        }
        return result;
    }

    /**
     * 获取验证码并存放在Redis中
     * @Author 二饭
     * @Email 1786705138@qq.com
     * @Date 2021/12/6 20:33
     */
    @GetMapping("captcha")
    @ApiOperation("获取验证码图片")
    public RequestResult captcha() throws IOException {
        RequestResult result = new RequestResult();

        ArithmeticCaptcha captcha = new ArithmeticCaptcha(130, 48);
        captcha.setLen(3);  // 几位数运算，默认是两位
        captcha.getArithmeticString();  // 获取运算的公式：3+2=?
        captcha.text();  // 获取运算的结果：5

        // 生成UUID作为Key 将验证码的结果存在Redis中
        String key = UUID.randomUUID().toString().replaceAll("-", "");
        redisUtil.save(key,captcha.text(),1000*60*5L);

        // 构建返回客户端数据对象
        result.appendData("captcha",captcha.toBase64());
        result.appendData("key", key);

        return result;
    }


}
